<template>
  <div class="flowpath-container">
    <div>
      <div class="mb20">
        <span class="color_494949 ft12 pr5">{{ translate('关键字') }}：</span>
        <el-input
          v-model="searchInfo"
          class="w164 mr10"
          :placeholder="translate('请输入关键字')"
        />
        <el-button class="settingBtn" type="primary" @click="getList">
          {{ translate('查询') }}
        </el-button>
      </div>
      <div class="add">
        <el-button
          v-if="MenuAuths('add')"
          class="settingBtn"
          type="primary"
          @click="addFn"
          plain
        >
          {{ translate('新增') }}
        </el-button>
        <el-upload
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          :action="action"
          :before-upload="beforeUpload"
          class="ml-upload"
          :headers="headers"
          name="fileInput"
          :on-error="handleError"
          :on-success="handleSuccess"
          :show-file-list="false"
        >
          <ElButton type="primary" @click="uploadFn()" plain>
            {{ translate('导入') }}
          </ElButton>
        </el-upload>
        <el-button
          v-if="MenuAuths('add')"
          class="settingBtn"
          type="primary"
          @click="download"
          plain
        >
          {{ translate('导出') }}
        </el-button>
        <!-- <el-button
          class="settingBtn"
          type="primary"
          @click="batchFn"
          plain
        >
          {{ translate('批量审核') }}
        </el-button> -->
      </div>
      <el-table :data="tableData"
                :row-class-name="tableRowClassName"
                :row-key="getRowKey"
                @selection-change="handleSelectionChange">
        <el-table-column prop="value" type="selection" width="55" />
        <!-- <el-table-column label="序号" type="index" width="80" /> -->
        <el-table-column
          :label="translate('盘点名称')"
          prop="FullName"
          show-overflow-tooltip
        />
        <el-table-column :label="translate('盘点编码')" width="250">
          <template #default="{ row }">
            <div v-if="row.Code">
              <span class="iconcolor">{{ row.Code }}</span>
              <vab-icon icon="file-copy-line" @click="copyToClipboard(row.Code)" />
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="translate('盘点编号')" width="250">
          <template #default="{ row }">
            <div v-if="row.CONo">
              <span class="iconcolor">{{ row.CONo }}</span>
              <vab-icon icon="file-copy-line" @click="copyToClipboard(row.CONo)" />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          :label="translate('盘点仓库')"
          prop="CheckWH"
          show-overflow-tooltip
        />
        <el-table-column
          :label="translate('盘点时间')"
          prop="CheckDate"
          show-overflow-tooltip
        />
        <el-table-column :label="translate('审核状态')" show-overflow-tooltip>
          <template #default="{ row }">
            <div>
              <el-tag type="success" v-if="row.Remark === '已审核'">{{ row.Remark }}</el-tag>
              <el-tag type="danger" v-if="row.Remark === '已结束'">{{ row.Remark }}</el-tag>
              <el-tag type="info" v-if="row.Remark && row.Remark !== '已审核' && row.Remark !== '已结束'">{{ row.Remark }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="translate('操作')" width="250">
          <template #default="{ row }">
            <el-button plain size="small" type="primary" @click="examineFn(row)">
              {{ translate('审核') }}
            </el-button>
            <el-button
              v-if="MenuAuths('edit')"
              plain
              size="small"
              type="primary"
              @click="detailFn(row)"
            >
              {{ translate('编辑') }}
            </el-button>
            <el-button
              v-if="MenuAuths('delete')"
              plain
              size="small"
              type="danger"
              @click="deletedFn(row)"
            >
              {{ translate('删除') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          :current-page="pageNo"
          :layout="layout"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      :title="translate('物资盘点明细')"
      width="1300px"
      @close="closeFn"
      :close-on-click-modal="false"
    >
      <i v-if="status === 1" class="iconfont icon-shenhezhong iconcommon"></i>
      <i v-if="status === 2" class="iconfont icon-yishenhe iconcommon2"></i>
      <detail
        :chileddetail="chileddetail"
        :form="form"
        @deletedchild="deletedchild"
      />
      <template #footer>
        <el-button @click="dialogVisible = false">
          {{ translate('取消') }}
        </el-button>
        <el-button type="primary" @click="submit">
          {{ translate('确定') }}
        </el-button>
      </template>
    </el-dialog>
    <wordflow
      :drawershow="isdrawershow"
      :formid="formId"
      :nodelist="nodeList"
      @handclose="handleClose"
    />
  </div>
</template>

<script>
  import {
    CheckOrderData,
    CheckOrderDel,
    UpdateCheckOrder,
    AddCheckOrder,
    CheckOrderDetail,
    startflow,
    auditwms,
    getinstance,
    InventoryExamine,
    InventoryBatchData,
    CheckOrderExport,
  } from '@/api/form'
  import detail from './components/detail'
  import wordflow from '@/views/components/wordflow/index'
  import { MenuAuth } from '~/src/utils/permission'
  import { translate } from '@/i18n'
  import { useUserStore } from '@/store/modules/user'
  import { baseURL } from '@/config'
  import { parseTime } from '@/utils'
  const { token } = useUserStore()
  export default defineComponent({
    name: 'Arrival',
    components: { detail, wordflow },
    data() {
      return {
        tableData: [],
        searchInfo: '',
        total: 0,
        pageNo: 1,
        pageSize: 20,
        dialogVisible: false,
        enabled: 0,
        DetailPageData: {},
        chileddetail: [],
        submitType: 'add',
        layout: 'total, sizes, prev, pager, next, jumper',
        deleList: [],
        COMId: '',
        MenuAuths: '',
        isdrawershow: false,
        nodeList: {},
        formId: '',
        status: -1,
        action: '',
        headers: '',
        selectArr: [],
        form: {
          Code: '',
          FullName: '',
          CONo: '',
          CheckWH: '',
          COType: '',
          CheckDate: '',
          CheckStatus: '',
        },
      }
    },
    created() {
      this.MenuAuths = MenuAuth
      this.getList()
    },
    methods: {
      //复制标识
      async copyToClipboard(val) {
        if (navigator.clipboard && window.isSecureContext) {
          try {
          console.log(navigator.clipboard)
          console.log(window.isSecureContext)
          await navigator.clipboard.writeText(val)
          this.$message({
            message:'复制成功',
            type:'success',
          })
          } catch (err) {
            this.$message({
            message:'复制失败',
            type:'error',
          })
          }

        }else {
          // 创建text area
        const textArea = document.createElement("textarea")
        textArea.value = val
        // 使text area不在viewport，同时设置不可见
        textArea.style.position = "absolute"
        textArea.style.opacity = 0
        textArea.style.left = "-999999px"
        textArea.style.top = "-999999px"
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()

        return new Promise((res, rej) => {
          // 执行复制命令并移除文本框
          document.execCommand("copy") ? res() : rej()
          textArea.remove()
        }).then(() => {
          this.$message({
              message: "复制成功",
              type: "success",
            })
          }).catch((err) => {
            this.$message({
              message: "复制失败",
              type: "error",
            })
          })
        }

      },
      batchFn() {
        if(this.selectArr.length<=0){
          this.$message({
            message: translate('请选择要审核的单据'),
            type: 'warning',
          })
          return
        }else {
          console.log(this.selectArr)
          this.InComeBatch()
        }
      },
       // 下载物资表
       async download() {
        let selectList = []
        if(this.selectArr && this.selectArr.length > 0) {
           this.selectArr.map(item =>{
            selectList.push(item.CONo)
           })
        }
        const params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          tableName: '',
          sort: '',
          order: '',
          wheres: JSON.stringify([
            { name: 'Code', value: this.searchInfo, displayType: 'like' },
          ]),
          export: false,
          value: selectList.length>0?selectList.join(','):'',
        }
        const data = await CheckOrderExport(params)
        const time = parseTime(new Date().getTime(), '{y}{m}{d}{h}{i}{s}')
        const blob = new Blob([data])
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.download = `物资盘点单${time}.xlsx`
        link.href = url
        link.click()
      },
      async InComeBatch() {
        const formIdArr = []
        this.selectArr.map((item,index) =>{
             formIdArr.push(
              {
                formId: item.COMId
              }
             )
        })
        const params = formIdArr
        const data = await InventoryBatchData(params)
        if(data.result.code === '200'){
          this.$message({
            message: translate('已提交审核'),
            type: 'success',
          })
          this.getList()
        }else {
          this.$message({
            message: data.result.message,
            type: 'error',
          })
        }
        console.log(data)
      },
      async uploadFn() {
        this.headers = this.headers = {
          Authorization: `Bearer ${token}`,
        }
        this.action = `${baseURL}/Wms_CheckOrderMaster/ImportNew?tablename=checkorder`
      },
      handleError(data) {
        console.log(data)
      },
      handleSuccess(data) {
        console.log(data)
        if (data.code === '200') {
          this.$message({
            type: 'success',
            message: data.message,
          })
          this.getList()
        } else {
          this.$message({
            message: data.message,
            type: 'error',
          })
        }
      },
      translate(row) {
        return translate(row)
      },
      handleClose() {
        this.isdrawershow = false
      },
      async examineFn(row) {
        this.$confirm(translate('确认提交?'), translate('提示'), {
          confirmButtonText: translate('确定'),
          cancelButtonText: translate('取消'),
          type: 'warning',
        })
          .then(() => {
            this.InventoryExamines(row)
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: translate('已取消删除'),
            })
          })
        // const params = {
        //   keyValue: row.COMId,
        //   code: 'Wms_CheckOrderMaster',
        //   formUrl: 'outboundBill',
        //   flowData: null,
        // }
        // const data = await startflow(params)
        // if (data.code === '200') {
        //   // this.auditwms('Wms_CheckOrderMaster', row.COMId)
        //   this.formId = row.COMId
        //   this.$router.push({
        //     path: '/table/detail',
        //     query: {
        //       formId: this.formId,
        //       formcode: 'Wms_CheckOrderMaster',
        //     },
        //   })
        // } else {
        //   this.$message({
        //     message: data.message,
        //     type: 'error',
        //   })
        // }
      },
      async InventoryExamines(row) {
        const params = {
          code: 'Wms_CheckOrderMaster',
          formId: row.COMId,
        }
        const data = await InventoryExamine(params)
        if (data.result.code === '200') {
          this.$message({
            message: translate('提交成功'),
            type: 'success',
          })
        }
      },
      async auditwms(Code, id) {
        const params = {
          code: Code,
          keyValue: id,
        }
        const data = await auditwms(params)
        if (data.code === '200') {
          this.nodeList = data.data
          this.isdrawershow = true
        } else {
          this.$message({
            message: data.message,
            type: 'error',
          })
        }
      },
      async getList() {
        const params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          tableName: '',
          sort: '',
          order: '',
          wheres: JSON.stringify([
            { name: 'FullName', value: this.searchInfo, displayType: 'like' },
          ]),
          export: false,
          value: '',
        }
        const data = await CheckOrderData(params)
        this.tableData = data.data.rows
        this.total = data.data.total
        console.log(this.tableData)
      },
      deletedchild(e) {
        this.deleList = e
        console.log(e)
      },
      deletedFn(row) {
        this.$confirm(translate('确认删除该文件吗?'), translate('提示'), {
          confirmButtonText: translate('确定'),
          cancelButtonText: translate('取消'),
          type: 'warning',
        })
          .then(() => {
            this.deleted(row)
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: translate('已取消删除'),
            })
          })
      },
      async deleted(row) {
        const COMId = []
        COMId.push(row.COMId)
        const params = COMId
        const data = await CheckOrderDel(params)
        if (data.code == '200') {
          this.$message({
            message: translate('删除成功'),
            type: 'success',
          })
          await this.getList()
        }
      },
      //分页条数切换
      handleSizeChange(val) {
        this.pageSize = val
        this.getList()
      },
      //分页切换
      handleCurrentChange(val) {
        this.pageNo = val
        this.getList()
      },
      tableRowClassName({ row, rowIndex }) {
        row.row_index = rowIndex
      },
      handleSelectionChange(e) {
        this.selectArr = e
      },
      getRowKey(row) {
        return row.COMId
      },
      async addFn() {
        this.deleList = []
        this.submitType = 'add'
        this.status = -1
        this.form = {
          Code: '',
          FullName: '',
          CONo: '',
          CheckWH: '',
          COType: '',
          CheckDate: '',
          CheckStatus: '',
        }
        this.chileddetail = []
        this.dialogVisible = true
      },
      submit() {
        if (this.status === 1 || this.status === 2) {
          const messages =
            this.status === 1
              ? '单据审核中，不允许修改！'
              : '单据已审核，不允许修改'
          this.$message({
            message: messages,
            type: 'warning',
          })
          return
        }
        if (this.submitType === 'add') {
          this.AddCheckOrder()
        } else {
          this.updataSaveList()
        }
      },
      closeFn() {
        this.enabled = 0
        this.form.WorkFlowID = ''
      },
      async detailFn(row) {
        this.deleList = []
        this.form = row
        this.COMId = row.COMId
        this.submitType = 'edit'
        await this.getinstances(row)
        await this.CheckOrderDetail()
        this.dialogVisible = true
        console.log(this.form)
      },
      async getinstances(row) {
        const params = {
          code: 'Wms_CheckOrderMaster',
          formId: row.COMId,
        }
        const data = await getinstance(params)
        if (data.code === '200') {
          this.status = data.data?.data?.status
        }
      },
      async CheckOrderDetail() {
        const params = {
          pageNo: 1,
          pageSize: 5000,
          total: 0,
          tableName: '',
          sort: '',
          order: '',
          wheres: '',
          export: true,
          value: this.COMId,
        }
        const data = await CheckOrderDetail(params)
        if (data.master) {
          this.$nextTick(() => {
            this.chileddetail = data.rows
          })
        }
        console.log(data)
      },
      async AddCheckOrder() {
        const params = {
          mainData: this.form,
          detailData: this.chileddetail,
          delKeys: [],
        }
        const data = await AddCheckOrder(params)
        if (data.code == '200') {
          this.getList()
          this.$message({
            message: translate('保存成功'),
            type: 'success',
          })
          this.dialogVisible = false
        }
      },
      async updataSaveList() {
        const params = {
          mainData: this.form,
          detailData: this.chileddetail,
          delKeys: this.deleList,
        }
        const data = await UpdateCheckOrder(params)
        if (data.code == '200') {
          this.getList()
          this.$message({
            message: translate('保存成功'),
            type: 'success',
          })
          this.dialogVisible = false
        }
      },
    },
  })
</script>
<style lang="scss" scoped>
  .flowpath-container {
    .color_494949 {
      color: #494949;
    }
    .w164 {
      width: 164px;
    }
    .mb20 {
      margin-bottom: 20px;
    }
    .mr10 {
      margin-right: 10px;
    }
    .iconcommon {
      position: absolute;
      top: 80px;
      right: 70px;
      font-size: 60px;
      color: blue;
    }
    .iconcommon2 {
      position: absolute;
      top: 80px;
      right: 70px;
      font-size: 60px;
      color: red;
    }
    .ml-upload {
      display: inline-block;
      margin-left: 10px;
      vertical-align: bottom;
      margin-right: 10px;
    }
    .add {
      margin-bottom: 10px;
      text-align: left;
    }
    .iconcolor {
      color: #409eff;
    }
  }
</style>
